﻿#include "JistTableView.h"
#include "JistDocumentHandler.h"
#include "MoveData.h"
#include "AddCell.h"
#include "ChangeSelection.h"
#include "JistAniTool.h"
#include "../documentmanager.h"
#include "../libtiled/objectgroup.h"
#include "../libtiled/mapobject.h"
#include "../mapscene.h"
#include "../addremovemapobject.h"
#include "../utils.h"
#include "../propertiesdialog.h"
#include "../changeproperties.h"

#include <QWidget>
#include <QMenu>

JistTableView::JistTableView(ChangeStyle ch, QWidget *parent) :
    QTableView(parent),
    m_iSelectIndex(-1),
    m_isUndoAction(false),
    m_isSelcetChanging(false)
{
    m_eChangeMode = ch;
    //connect(this, SIGNAL(changeSelectRow(int)), this, SLOT(selectRow(int)));

    m_TextEditdialog = new QDialog(this);
    m_TextEdit = new QTextEdit();
    QVBoxLayout *subLayout = new QVBoxLayout;
    subLayout->addWidget(m_TextEdit);
     QDialogButtonBox *buttonBox;
     buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
                                     | QDialogButtonBox::Cancel);

    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
    subLayout->addWidget(buttonBox);
    m_TextEditdialog->setLayout(subLayout);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(m_TextEditdialog);
    setLayout(mainLayout);
    m_TextEditdialog->setVisible(false);
    m_TextEditdialog->setModal(true);

    setSelectionBehavior(QAbstractItemView::SelectRows);
    setSelectionMode(QAbstractItemView::ExtendedSelection);
}

void JistTableView::setSelection ( const QRect & rect, QItemSelectionModel::SelectionFlags flags )
{
    if(m_eChangeMode != CELLLIST_CHANGE)
    {
        QTableView::setSelection (rect, flags );
    }
    else{
        QRect tempRect =  this->rect();
        int sValue = rect.bottom() - tempRect.bottom();

        QScrollBar *hb = horizontalScrollBar();
        int hValue = ((QAbstractSlider*)hb)->value();

        QScrollBar *vb = this->verticalScrollBar();
        ((QAbstractSlider*)vb)->setSliderPosition(0);
        if(sValue > 0)
            ((QAbstractSlider*)vb)->setSliderPosition(sValue/(JistCommonDelegate::m_PixelSize + 1)  + 1);
        else
            sValue = 0;
        int vValue = ((QAbstractSlider*)vb)->sliderPosition();
        QRect resultRect = rect;

        resultRect.setRect(rect.x(), rect.y() - sValue, 1 , 1);
        QTableView::setSelection (resultRect, flags );

    }
}

void JistTableView::selectionChanged ( const QItemSelection & selected, const QItemSelection & deselected )
{
    QTableView::selectionChanged(selected, deselected);
    m_iSelectIndex = currentIndex().row();//(JistCommonModel*)(this->model()))->toModelIndex(currentIndex());
    JistDocumentHandler *handler = JistDocumentHandler::instance();
    switch(m_eChangeMode)
    {
        case SPRITELIST_CHANGE:
        {
            m_pDocument->setSpriteView(currentIndex());
            emit currentCellChanged(m_pDocument->getCurrentSpriteData());
            break;
        }

        case IMGLIST_CHANGE:
        {
            m_pDocument->changeSpriteList(currentIndex().row());
            break;
        }

        case ANIMATIONLIST_CHANGE:
        {
            if((m_iSelectIndex != m_pDocument->m_iCurrentSceneDataIndex && !m_isUndoAction && !selected.isEmpty())){
                    emit changeSelectRow(m_pDocument->m_iCurrentSceneDataIndex);
            }

            m_pDocument->changeSceneList(currentIndex().row());
            handler->actionAddScene()->setEnabled(true);
            setFocus();
            break;
        }

        case SCENELIST_CHANGE:
        {
            if((m_iSelectIndex != m_pDocument->m_iCurrentCellDataIndex && !m_isUndoAction && !selected.isEmpty())){
                    emit changeSelectRow(m_pDocument->m_iCurrentCellDataIndex);
                    //m_isUndoAction = true;
            }

            m_pDocument->changeCellList(currentIndex().row());
            setFocus();
            break;
        }

        case CELLLIST_CHANGE:
        {
//            if(selected.indexes().count() > 0)
//                setCurrentIndex(selected.indexes().last());
            m_pDocument->changeCellData(selected, deselected);
            break;
        }
    }
}

void JistTableView::setDocument(JistDocument *document)
{
    m_pDocument = document;
}



void JistTableView::contextMenuEvent(QContextMenuEvent *event)
{
    JistDocumentHandler *handler = JistDocumentHandler::instance();

    QMenu menu;

    switch(m_eChangeMode)
    {
        case SPRITELIST_CHANGE:
        {
            if(currentIndex().row() != -1 && m_pDocument->m_SceneTableWidget && m_pDocument->m_SceneTableWidget->currentIndex().row() != -1)
                handler->actionAddCell()->setEnabled(true);
            else
                handler->actionAddCell()->setEnabled(false);

            int index = currentIndex().row();
            JistCommonModel* m = (JistCommonModel*)(this->model());
            JistCommonData data = m->m_pList->value(index);
//            char *menuStr = "다듬기";
//            char *menuUndoStr = "되돌리기";

//            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
//            QString localeStr = codec->toUnicode(menuStr);
//            QString localeUndoStr = codec->toUnicode(menuUndoStr);
//            handler->actionSetUIOptCut_WW()->setText(localeStr);
//            handler->actionSetUIOptCut_WH()->setText(localeStr);
//            handler->actionSetUIOptCut_NW()->setText(localeStr);
//            handler->actionSetUIOptCut_NH()->setText(localeStr);
//            handler->actionSetUIOptCut_WH()->setChecked(false);
//            if(data.m_UIOpt & 0x1){
//                handler->actionSetUIOptCut_WW()->setText(localeUndoStr);
//            }
//            if(data.m_UIOpt & 0x2){
//                handler->actionSetUIOptCut_WH()->setChecked(true);
//                handler->actionSetUIOptCut_WH()->setText(localeUndoStr);
//            }
//            if(data.m_UIOpt & 0x4){
//                handler->actionSetUIOptCut_NW()->setText(localeUndoStr);
//            }
//            if(data.m_UIOpt & 0x8){
//                handler->actionSetUIOptCut_NH()->setText(localeUndoStr);
//            }
//            menu.addAction(handler->actionAddCell());
//            menu.addAction(handler->actionSetUIOptCut_WW());
//            menu.addAction(handler->actionSetUIOptCut_WH());
//            menu.addAction(handler->actionSetUIOptCut_NW());
//            menu.addAction(handler->actionSetUIOptCut_NH());
//            menu.addAction(handler->mActionAddShadowCell);
            // seok 프로퍼티
            char *menuStr = "속성";
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
            QString localeStr = codec->toUnicode(menuStr);
            QIcon propIcon(QLatin1String(":images/16x16/document-properties.png"));
            QAction *objDataProperties = menu.addAction(propIcon,
                                                     localeStr);
            //tileProperties->setEnabled(!isExternal);
            Tiled::Utils::setThemeIcon(objDataProperties, "document-properties");
            menu.addSeparator();

            connect(objDataProperties, SIGNAL(triggered()),
                    SLOT(editProperties()));

            char *menuStrObjs = "오브젝트에 적용";
            localeStr = codec->toUnicode(menuStrObjs);
            QIcon refPropIcon(QLatin1String(":images/24x24/document-ref-properties.png"));
            QAction *objRefProperties = menu.addAction(refPropIcon,
                                                    localeStr);
            //tileProperties->setEnabled(!isExternal);
            Tiled::Utils::setThemeIcon(objRefProperties, "document-ref-properties");

            connect(objRefProperties, SIGNAL(triggered()),
                    SLOT(editRefProperties()));

            menu.exec(event->globalPos());
            break;
        }
        case IMGLIST_CHANGE:
        {
            menu.addAction(handler->actionAddImage());
            menu.addAction(handler->actionDeleteImage());
            menu.addAction(handler->actionFakeBmp());
            menu.addAction(handler->mActionSetImgName);

            // seok 프로퍼티
            char *menuStr = "속성";
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
            QString localeStr = codec->toUnicode(menuStr);
            QIcon propIcon(QLatin1String(":images/16x16/document-properties.png"));
            QAction *objDataProperties = menu.addAction(propIcon,
                                                     localeStr);
            //tileProperties->setEnabled(!isExternal);
            Tiled::Utils::setThemeIcon(objDataProperties, "document-properties");
            menu.addSeparator();

            connect(objDataProperties, SIGNAL(triggered()),
                    SLOT(editProperties()));

            menu.exec(event->globalPos());
            break;
        }
        case ANIMATIONLIST_CHANGE:
        {
            menu.addAction(handler->actionAddAnimation());
            menu.addAction(handler->actionSetAniName());
            menu.exec(event->globalPos());
            break;
        }
        case SCENELIST_CHANGE:
        {
            menu.addAction(handler->actionAddScene());
            menu.addAction(handler->mActionSetSceneName);
            menu.exec(event->globalPos());
            break;
        }
        case CELLLIST_CHANGE:
            menu.addAction(handler->actionMoveLayerUp());
            menu.addAction(handler->actionMoveLayerDown());
            menu.addAction(handler->actionAddEmptyCell());
            menu.addAction(handler->mActionSetCellName);
            menu.exec(event->globalPos());
            break;
    }
}

// seok 프로퍼티
void JistTableView::editProperties()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    QList< JistCommonData > *pList = m->m_pList;
    JistCommonData *data = &((*pList)[index]);
    Tiled::Internal::DocumentManager *docMan =  Tiled::Internal::DocumentManager::instance();
    Tiled::Internal::MapScene *curScene = docMan->currentMapScene();
    switch(m_eChangeMode)
    {
        case IMGLIST_CHANGE:
        {
            Tiled::Internal::PropertiesDialog propertiesDialog(tr("ImageSet"),
                                              &data->m_Object,
                                              docMan->currentDocument()->undoStack(),
                                              0);
            propertiesDialog.exec();
        }break;
        case SPRITELIST_CHANGE:
        {
            Tiled::Internal::PropertiesDialog propertiesDialog(tr("JistCell"),
                                              &data->m_Object,
                                              docMan->currentDocument()->undoStack(),
                                              0);
            propertiesDialog.exec();
            QString name = data->m_Object.properties().value(QString(tr("name")));
            data->SetName(name);
            int x = data->m_Object.properties().value(QString(tr("ancX"))).toInt();
            data->m_AnchorPoint.setX(x);
            int y = data->m_Object.properties().value(QString(tr("ancY"))).toInt();
            data->m_AnchorPoint.setY(y);
            m_pDocument->setSpriteView(currentIndex());
            curScene->syncAllObjectItems();
        }break;
    }
}

void JistTableView::editRefProperties()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    QList< JistCommonData > *pList = m->m_pList;
    JistCommonData *data = &((*pList)[index]);
    Tiled::Internal::DocumentManager *docMan =  Tiled::Internal::DocumentManager::instance();
    // seok 오브젝트 리스트와 오브젝트의 연동
    int srciid = data->m_iImgIndex;
    int srcsid = data->m_iSpriteIndex;
    int groupCnt = 0;
    Tiled::Internal::MapDocument *mapDoc = docMan->currentDocument();
    QList<Tiled::ObjectGroup*> groups = mapDoc->map()->objectGroups();

    int objCnt = 0;
    while (groupCnt < groups.count()){
        Tiled::ObjectGroup* tempGroup = groups.at(groupCnt++);
        foreach (Tiled::MapObject *object, tempGroup->objects())
        {
            if (object->jistCell()) {
                const unsigned iid = object->jistCell()->m_iImgIndex;
                const unsigned sid = object->jistCell()->m_iSpriteIndex;
                if(iid == srciid && sid == srcsid){

                    const Tiled::Properties &properties = data->m_Object.properties();
                    // 이름 넣기
                    QString name = properties.value(QString(tr("name")));
                   // if(!name.isNull()){
                        object->setName(name);
                   // }

                    if (object->properties() != properties) {
                        docMan->currentDocument()->undoStack()->push(new Tiled::Internal::ChangeProperties(tr("Ref_obj"),
                                                              object,
                                                              properties));
                        objCnt++;
                        // 이름 빼기
                        object->propertiesEx().remove(QString(tr("name")));
                        // anchor정보 빼기
                        object->propertiesEx().remove(QString(tr("ancX")));
                        object->propertiesEx().remove(QString(tr("ancY")));
                    }
                }
            }
        }
    }
    qDebug("obj Property change %d", objCnt);
}

// 원더런 오브젝트 이미지 순서 변경후 인덱스 동기화
void JistTableView::SyncObjectImgIndex(int currentIdx, int moveIdx)
{
    Tiled::Internal::DocumentManager *docMan =  Tiled::Internal::DocumentManager::instance();

    Tiled::Internal::MapDocument *mapDoc = docMan->currentDocument();
    QList<Tiled::ObjectGroup*> groups = mapDoc->map()->objectGroups();
    int groupCnt = 0;
    while (groupCnt < groups.count()){
        Tiled::ObjectGroup* tempGroup = groups.at(groupCnt++);
        foreach (Tiled::MapObject *object, tempGroup->objects())
        {
            if (object->jistCell()) {
                // 임시 인덱스로 처리해야함
                const unsigned iid = object->GetImgIndex() - 1;
                if(iid == currentIdx){
                    object->jistCell()->m_iImgIndex = moveIdx;
                    object->SetImgIndex(moveIdx+1);
                }else if(iid == moveIdx)
                {
                    object->jistCell()->m_iImgIndex = currentIdx;
                    object->SetImgIndex(currentIdx+1);
                }
            }
        }
    }
}

// 원더런 오브젝트 스프라이트 순서 변경후 인덱스 동기화
void JistTableView::SwapSprite(int currentIdx, int moveIdx)
{
    int index = currentIdx;//currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    QList< JistCommonData > *pList = m->m_pList;
    JistCommonData *data = &((*pList)[index]);
    JistCommonData *moveData = &((*pList)[moveIdx]);

    Tiled::Internal::DocumentManager *docMan =  Tiled::Internal::DocumentManager::instance();
    Tiled::Internal::MapDocument *mapDoc = docMan->currentDocument();
    QList<Tiled::ObjectGroup*> groups = mapDoc->map()->objectGroups();
    // seok 오브젝트 리스트와 오브젝트의 연동
    int srciid = data->m_iImgIndex;
    int srcsid = data->m_iSpriteIndex;
    int moveiid = moveData->m_iImgIndex;
    int movesid = moveData->m_iSpriteIndex;
    // 실제 인덱스 변경
    data->m_iImgIndex = moveiid;
    data->m_iSpriteIndex = movesid;
    // 실제 인덱스 변경
    moveData->m_iImgIndex = srciid;
    moveData->m_iSpriteIndex = srcsid;
    int groupCnt = 0;
    while (groupCnt < groups.count()){
        Tiled::ObjectGroup* tempGroup = groups.at(groupCnt++);
        foreach (Tiled::MapObject *object, tempGroup->objects())
        {
            if (object->jistCell()) {
                // 임시 인덱스 동기화
                const unsigned sid = object->jistCell()->GetSpriteIndex(); // 실제 인덱스
                const unsigned tempIdx = object->GetSpriteIndex() - 1; // 임시 인덱스
                if(sid != tempIdx){
                    object->SetImgIndex(sid + 1); // 임시인덱스 관리
                }

//                const unsigned sid = object->jistCell()->GetSpriteIndex();
//                if(sid == currentIdx){
//                    object->jistCell()->SetSpriteIndex(moveIdx);
//                    object->SetSpriteIndex(moveIdx+1);
//                }else if(sid == moveIdx)
//                {
//                    object->jistCell()->SetSpriteIndex(currentIdx);
//                    object->SetSpriteIndex(currentIdx+1);
//                }
            }
        }
    }
}


QModelIndexList JistTableView::selectedIndexes () const
{
    return QTableView::selectedIndexes ();
}


void JistTableView::refineView(int index)
{
    clearFocus();
    m_isUndoAction = true;
	//로딩후 마지막 애니메이션 위로 이동시 다운버그 수정
    //clearSelection();
    if(this->model()->rowCount())
       setFocus();
    m_isUndoAction = false;
    selectRow(index);
    //m_isUndoAction = true;

    resizeColumnsToContents();
    resizeRowsToContents();
}

void JistTableView::refineViewNoUndo(int index)
{
    clearFocus();
    if(!m_pDocument->m_isLoading)
        clearSelection();
    if(this->model()->rowCount())
       setFocus();
    m_isUndoAction = true;
    selectRow(index);

    resizeColumnsToContents();
    resizeRowsToContents();
    m_isUndoAction = false;
}

// 리스트 아이템이동
void JistTableView::moveItemUp()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    if (index <= 0 || index >= m->rowCount())
        return;

//    switch(m_eChangeMode)
//    {
//        case ANIMATIONLIST_CHANGE:
//        {
//            int moveIndex = index - 1;
//            // 셀리스트뷰에 대한 갱신
//            //스왑을 이용하기 위해 리스트로 변환
//            QList< QVector< QList< JistCommonData > > > tempCellList = m_pDocument->m_CellData.toList();
//            tempCellList.swap(index, moveIndex );
//            m_pDocument->m_CellData = tempCellList.toVector();
//            m_pDocument->m_CellListModel.setDataList(&m_pDocument->m_CellData[moveIndex][m_pDocument->m_iCurrentCellDataIndex]);
//            m_pDocument->m_CellTableWidget->refineView(0);
//            // 신리스트뷰에 대한 갱신
//            QList< QList < JistCommonData> > tempList = m_pDocument->m_SceneData.toList();
//            tempList.swap(index, moveIndex );
//            m_pDocument->m_SceneData = tempList.toVector();
//            m_pDocument->m_SceneListModel.setDataList(&m_pDocument->m_SceneData[moveIndex]);
//            refineView(moveIndex);
//            break;
//        }
//        case SCENELIST_CHANGE:
//        {
//            int moveIndex = index - 1;
//            // 셀리스트뷰에 대한 갱신
//            //스왑을 이용하기 위해 리스트로 변환
//            QList< QList< JistCommonData > >  tempCellList = m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex].toList();
//            if(tempCellList.at(index).isEmpty() || tempCellList.at(moveIndex).isEmpty())
//                return;
//            tempCellList.swap(index, moveIndex );
//            m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex] = tempCellList.toVector();
//            m_pDocument->m_CellListModel.setDataList(&m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex][moveIndex]);
//            //m_pDocument->m_CellTableWidget->refineView(0);
//            break;
//        }
//    }
    m_pDocument->undoStack()->push(new MoveData(m_pDocument, index, MoveData::Up, this));
}

void JistTableView::moveItemDown()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    if (index < 0 || index >= m->rowCount() - 1)
        return;

//    switch(m_eChangeMode)
//    {
//        case ANIMATIONLIST_CHANGE:
//        {
//            int moveIndex = index + 1;
//            // 셀리스트뷰에 대한 갱신
//            QList< QVector< QList< JistCommonData > > > tempCellList = m_pDocument->m_CellData.toList();
//            tempCellList.swap(index, moveIndex );
//            m_pDocument->m_CellData = tempCellList.toVector();
//			m_pDocument->m_CellListModel.setDataList(&m_pDocument->m_CellData[moveIndex][m_pDocument->m_iCurrentCellDataIndex]);
//            m_pDocument->m_CellTableWidget->refineView(0);
//            // 신리스트뷰에 대한 갱신
//            QList< QList < JistCommonData> > tempList = m_pDocument->m_SceneData.toList();
//            tempList.swap(index, moveIndex );
//            m_pDocument->m_SceneData = tempList.toVector();
//            m_pDocument->m_SceneListModel.setDataList(&m_pDocument->m_SceneData[moveIndex]);
//            refineView(moveIndex);
//            break;
//        }
//        case SCENELIST_CHANGE:
//        {
//            int moveIndex = index + 1;
//            // 셀리스트뷰에 대한 갱신
//            //스왑을 이용하기 위해 리스트로 변환
//            QList< QList< JistCommonData > >  tempCellList = m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex].toList();
//            if(tempCellList.at(index).isEmpty() || tempCellList.at(moveIndex).isEmpty())
//                return;
//            tempCellList.swap(index, moveIndex );
//            m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex] = tempCellList.toVector();
//            m_pDocument->m_CellListModel.setDataList(&m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex][moveIndex]);
//            //m_pDocument->m_CellTableWidget->refineView(0);
//            break;
//        }
//    }
    m_pDocument->undoStack()->push(new MoveData(m_pDocument, index, MoveData::Down, this));
}


void JistTableView::copyCellItem()
{
    int index = currentIndex().row();
//    JistCommonModel* m = (JistCommonModel*)(this->model());
    if (index < 0 )//|| index >= m->rowCount() - 1)
        return;
    //emit changeSelectRow(m_pDocument->m_iCurrentCellDataIndex);
    QUndoCommand *cmd =  new AddCell(m_pDocument, index, this);
    cmd->setText(tr("Copy Cell"));
    m_pDocument->undoStack()->push(cmd);
}

void JistTableView::deleteCellItem()
{
    int index = currentIndex().row();
//    JistCommonModel* m = (JistCommonModel*)(this->model());
    if (index < 0 )//|| index >= m->rowCount() - 1)
        return;
    //emit changeSelectRow(m_pDocument->m_iCurrentCellDataIndex);
    QUndoCommand *cmd =  new RemoveCell(m_pDocument, index, this);
    cmd->setText(tr("delete Cell"));
    m_pDocument->undoStack()->push(cmd);

}

void JistTableView::setOptCut_WW()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    JistCommonData data = m->m_pList->value(index);
    // 짝수크기의 텍스쳐만들기
    if(!(data.m_UIOpt & 0x1) && data.m_Rect.width() % 2){
        //data.m_Rect.setWidth(data.m_Rect.width() + 1);
        data.m_Rect.setX(data.m_Rect.x() - 2);
        data.m_Rect.setRight(data.m_Rect.right() + 1);
        data.m_UIOpt |= 0x1;
        // 다듬어진 셀의 좌표 재 설정
        int currentImgIndex = m_pDocument->m_iCurrentSpriteDataIndex;
        int currentSpriteIndex = index;
        for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
            for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
                for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                    int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                    int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;

                    if(currentImgIndex == imgId && currentSpriteIndex == spriteId){
                        if(m_pDocument->m_CellData[a][s][c].m_pIItem->m_FlipH){
                           QPoint tempPos =  m_pDocument->m_CellData[a][s][c].m_pIItem->pos().toPoint();
                            m_pDocument->m_CellData[a][s][c].m_pIItem->setPos(QPointF(tempPos.x() + 1, tempPos.y()));
                        }
                    }
                }
            }
        }
    }
    else if((data.m_UIOpt & 0x1) ){//되돌리기
        //data.m_Rect.setWidth(data.m_Rect.width() - 1);
        data.m_Rect.setX(data.m_Rect.x() + 2);
        data.m_Rect.setRight(data.m_Rect.right() - 1);
        data.m_UIOpt &= 0xE;
        // 다듬어진 셀의 좌표 재 설정
        int currentImgIndex = m_pDocument->m_iCurrentSpriteDataIndex;
        int currentSpriteIndex = index;
        for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
            for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
                for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                    int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                    int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;

                    if(currentImgIndex == imgId && currentSpriteIndex == spriteId){
                        if(m_pDocument->m_CellData[a][s][c].m_pIItem->m_FlipH){
                           QPoint tempPos =  m_pDocument->m_CellData[a][s][c].m_pIItem->pos().toPoint();
                            m_pDocument->m_CellData[a][s][c].m_pIItem->setPos(QPointF(tempPos.x() - 1, tempPos.y()));
                        }
                    }
                }
            }
        }
    }
    else
        return;

    int imgTblIndex = m_pDocument->m_ImageTableWidget->currentIndex().row();
    QImage  cutImage = m_pDocument->m_ImageData[imgTblIndex].m_img.copy(data.m_Rect);
    data.m_img = cutImage;
    m->setData(currentIndex(),data.m_Rect, Qt::UserRole);
    m->setData(currentIndex(),data.m_img, Qt::UserRole+2);
    m->setData(currentIndex(),data.m_UIOpt, Qt::UserRole+3);
    m_pDocument->setSpriteView(currentIndex());
 }

void JistTableView::setOptCut_WH()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    JistCommonData data = m->m_pList->value(index);
    // 짝수크기의 텍스쳐만들기
    if(!(data.m_UIOpt & 0x2) && data.m_Rect.height() % 2){
        //data.m_Rect.setHeight(data.m_Rect.height() + 1);
        data.m_Rect.setY(data.m_Rect.y() - 2);
        data.m_Rect.setBottom(data.m_Rect.bottom() + 1);
        data.m_UIOpt |= 0x2;
        // 다듬어진 셀의 좌표 재 설정
        int currentImgIndex = m_pDocument->m_iCurrentSpriteDataIndex;
        int currentSpriteIndex = index;
        for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
            for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
                for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                    int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                    int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;

                    if(currentImgIndex == imgId && currentSpriteIndex == spriteId){
                        if(m_pDocument->m_CellData[a][s][c].m_pIItem->m_FlipV){
                           QPoint tempPos =  m_pDocument->m_CellData[a][s][c].m_pIItem->pos().toPoint();
                            m_pDocument->m_CellData[a][s][c].m_pIItem->setPos(QPointF(tempPos.x(), tempPos.y() + 1));
                        }
                    }
                }
            }
        }
    }
    else if((data.m_UIOpt & 0x2) ){//되돌리기
        //data.m_Rect.setHeight(data.m_Rect.height() - 1);
        data.m_Rect.setY(data.m_Rect.y() + 2);
        data.m_Rect.setBottom(data.m_Rect.bottom() - 1);
        data.m_UIOpt &= 0xD;
        // 다듬어진 셀의 좌표 재 설정
        int currentImgIndex = m_pDocument->m_iCurrentSpriteDataIndex;
        int currentSpriteIndex = index;
        for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
            for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
                for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                    int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                    int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;

                    if(currentImgIndex == imgId && currentSpriteIndex == spriteId){
                        if(m_pDocument->m_CellData[a][s][c].m_pIItem->m_FlipV){
                           QPoint tempPos =  m_pDocument->m_CellData[a][s][c].m_pIItem->pos().toPoint();
                            m_pDocument->m_CellData[a][s][c].m_pIItem->setPos(QPointF(tempPos.x(), tempPos.y() - 1));
                        }
                    }
                }
            }
        }
    }
    else
        return;

    int imgTblIndex = m_pDocument->m_ImageTableWidget->currentIndex().row();
    QImage  cutImage = m_pDocument->m_ImageData[imgTblIndex].m_img.copy(data.m_Rect);
    data.m_img = cutImage;
    m->setData(currentIndex(),data.m_Rect, Qt::UserRole);
    m->setData(currentIndex(),data.m_img, Qt::UserRole+2);
    m->setData(currentIndex(),data.m_UIOpt, Qt::UserRole+3);
    m_pDocument->setSpriteView(currentIndex());
 }


void JistTableView::setOptCut_NW()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    JistCommonData data = m->m_pList->value(index);
    // 짝수크기의 텍스쳐만들기
    if(!(data.m_UIOpt & 0x4)){// && data.m_Rect.width() % 2){
        data.m_Rect.setWidth(data.m_Rect.width() - 1);
        data.m_Rect.setX(data.m_Rect.x() + 1);
        data.m_UIOpt |= 0x4;
    }
    else if((data.m_UIOpt & 0x4) ){
        data.m_Rect.setWidth(data.m_Rect.width() + 1);
        data.m_Rect.setX(data.m_Rect.x() - 1);
        data.m_UIOpt &= 0xB;
    }
    else
        return;

    int imgTblIndex = m_pDocument->m_ImageTableWidget->currentIndex().row();
    QImage  cutImage = m_pDocument->m_ImageData[imgTblIndex].m_img.copy(data.m_Rect);
    data.m_img = cutImage;
    m->setData(currentIndex(),data.m_Rect, Qt::UserRole);
    m->setData(currentIndex(),data.m_img, Qt::UserRole+2);
    m->setData(currentIndex(),data.m_UIOpt, Qt::UserRole+3);
    m_pDocument->setSpriteView(currentIndex());
 }

void JistTableView::setOptCut_NH()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    JistCommonData data = m->m_pList->value(index);
    // 짝수크기의 텍스쳐만들기
    if(!(data.m_UIOpt & 0x8)){// && data.m_Rect.height() % 2){
        data.m_Rect.setHeight(data.m_Rect.height() - 1);
        data.m_Rect.setY(data.m_Rect.y() + 1);
        data.m_UIOpt |= 0x8;
    }
    else if((data.m_UIOpt & 0x8) ){
        data.m_Rect.setHeight(data.m_Rect.height() + 1);
        data.m_Rect.setY(data.m_Rect.y() - 1);
        data.m_UIOpt &= 0x7;
    }
    else
        return;

    int imgTblIndex = m_pDocument->m_ImageTableWidget->currentIndex().row();
    QImage  cutImage = m_pDocument->m_ImageData[imgTblIndex].m_img.copy(data.m_Rect);
    data.m_img = cutImage;
    m->setData(currentIndex(),data.m_Rect, Qt::UserRole);
    m->setData(currentIndex(),data.m_img, Qt::UserRole+2);
    m->setData(currentIndex(),data.m_UIOpt, Qt::UserRole+3);
    m_pDocument->setSpriteView(currentIndex());
 }

void JistTableView::copyCellList()
{
    int index = currentIndex().row();
    if (index < 0 )
        return;
    QList < JistCommonData> *sceneData = &m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex][m_pDocument->m_iCurrentCellDataIndex];
    QUndoCommand *cmd =  new AddCellList(m_pDocument, index, this, sceneData, &m_pDocument->m_SceneData[m_pDocument->m_iCurrentSceneDataIndex][m_pDocument->m_iCurrentCellDataIndex]);
    cmd->setText(tr("Copy Scene"));
    m_pDocument->undoStack()->push(cmd);
}

void JistTableView::deleteCellList()
{
    int index = currentIndex().row();
    if (index < 0 )
        return;
    QList < JistCommonData> *sceneData = &m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex][m_pDocument->m_iCurrentCellDataIndex];
    QUndoCommand *cmd =  new RemoveCellList(m_pDocument, index, this, sceneData, &m_pDocument->m_SceneData[m_pDocument->m_iCurrentSceneDataIndex][m_pDocument->m_iCurrentCellDataIndex]);
    cmd->setText(tr("delete Scene"));
    m_pDocument->undoStack()->push(cmd);
}

void JistTableView::emitChangeSelectRow(int index)
{
    emit changeSelectRow(index);
}

void JistTableView::changeSelection(int index)
{
    if (index < 0 )//|| index >= m->rowCount() - 1)
        return;
    QUndoCommand *cmd =  new ChangeSelection(this, index);
    cmd->setText(tr("ChangeSelection"));
    m_isUndoAction = false;
    m_pDocument->undoStack()->push(cmd);
}

void JistTableView::copyAnimation()
{
    int index = currentIndex().row();
    if (index < 0 )
        return;
    QList < JistCommonData> *sceneData = &m_pDocument->m_SceneData[m_pDocument->m_iCurrentSceneDataIndex];
    QVector< QList < JistCommonData > > *aniData = &m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex];
    QUndoCommand *cmd =  new CopyAnimation(m_pDocument, index, this, aniData, sceneData, &m_pDocument->m_AnimationData[m_pDocument->m_iCurrentSceneDataIndex]);
    cmd->setText(tr("Copy Animation"));
    m_pDocument->undoStack()->push(cmd);
}

void JistTableView::deleteAnimation()
{
    int index = currentIndex().row();
    if (index < 0 )
        return;
    QList < JistCommonData> *sceneData = &m_pDocument->m_SceneData[m_pDocument->m_iCurrentSceneDataIndex];
    QVector< QList < JistCommonData > > *aniData = &m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex];
    QUndoCommand *cmd =  new RemoveAnimation(m_pDocument, index, this, aniData, sceneData, &m_pDocument->m_AnimationData[m_pDocument->m_iCurrentSceneDataIndex]);
    cmd->setText(tr("delete Animation"));
    m_pDocument->undoStack()->push(cmd);
}

void JistTableView::deleteImage()
{
    Tiled::Internal::DocumentManager *docMan =  Tiled::Internal::DocumentManager::instance();
    int index = currentIndex().row();
    int groupCnt = 0;
    Tiled::Internal::MapDocument *mapDoc = docMan->currentDocument();
    QList<Tiled::ObjectGroup*> groups = mapDoc->map()->objectGroups();
    QUndoStack *undoStack = mapDoc->undoStack();
    //undoStack->beginMacro(tr("Remove %n Object(s)", "", objects.size()));
    undoStack->beginMacro(tr("Remove  Object(s)"));
    while (groupCnt < groups.count()){
        Tiled::ObjectGroup* tempGroup = groups.at(groupCnt++);
        int objCnt = 0;
        //while (xml.readNextStartElement()) {
        //while (objCnt < tempGroup->objects().count())
        foreach (Tiled::MapObject *object, tempGroup->objects())
        {
            // 오브젝트 로드
            //Tiled::MapObject *object = tempGroup->objects()[objCnt];

            if (object->jistCell()) {
                const unsigned iid = object->jistCell()->m_iImgIndex;
                //const unsigned sid = object->jistCell()->m_iSpriteIndex;
                if(iid == index){
                    qDebug("deleteImage %d", objCnt);
                    object->setCell(NULL);
                    undoStack->push(new Tiled::Internal::RemoveMapObject(mapDoc, object));
                }else if(iid > index){ // 지우는 이미지보다 인덱스가 크면 임시 이미지인덱스 1 감소
                    object->SetImgIndex(iid - 1);
                    object->jistCell()->m_iImgIndex = object->GetImgIndex()-1;
                }
            }
            objCnt++;
        }
    }
    undoStack->endMacro();
    Tiled::Internal::MapScene *curScene = docMan->currentMapScene();
//    // 이미지 인덱스 재설정
//    groupCnt = 0;
//    while (groupCnt < groups.count()){
//        Tiled::ObjectGroup* tempGroup = groups.at(groupCnt++);
//        int objCnt = 0;
//        foreach (Tiled::MapObject *object, tempGroup->objects())
//        {
//            if (object->jistCell()) {
//                const unsigned iid = object->GetImgIndex();
//                if(iid > index){ // 임시 인덱스로 재설정
//                    object->jistCell()->m_iImgIndex = iid;
//                }
//            }
//            objCnt++;
//        }
//    }
    curScene->syncAllObjectItems();

    if (index < 0 )
        return;
    JistCommonModel *dataModel = (JistCommonModel*)(this->model());
    dataModel->removeRow(index);
    m_pDocument->m_SpriteData[index].clear();
    m_pDocument->m_SpriteData.remove(index);
    int selIndex = index;
    if (index == dataModel->rowCount())
        selIndex = index - 1;
    if(selIndex >= 0)
        m_pDocument->m_SpriteListModel.setDataList(&m_pDocument->m_SpriteData[selIndex]);
    else{
        //m_pDocument->changeSpriteList(selIndex);

        // 이미지 리스트 정리
        m_pDocument->m_ImageListModel.reset();
        m_pDocument->m_ImageData.clear();
        m_pDocument->m_ImageListModel.setDataList(&m_pDocument->m_ImageData);

        // 스프라이트 리스트 정리
        m_pDocument->m_SpriteListModel.reset();
        for(int k = 0; k < m_pDocument->m_SpriteData.count(); k++){
            m_pDocument->m_SpriteData[k].clear();
        }
        //m_pDocument->clearAniList();
    }

    // 리스트뷰및 신뷰 갱신
    for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
        for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
            for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;
                // 지워진 스프라이트를 참조하는 셀 정리
                if(index == imgId){
                    // 빈 셀
                    (m_pDocument->m_CellData[a][s][c]).m_img = g_EmptyImage;// QImage();
                    (m_pDocument->m_CellData[a][s][c]).m_pIItem->m_SrcImage = NULL;
                }
                else if(imgId > index)
                  //(m_pDocument->m_CellData[a][s][c]).m_iImgIndex -= 1;
//                // 지워짐으로 변경되는 셀정리
//                if(imgId < m_pDocument->m_SpriteData.count() && spriteId < m_pDocument->m_SpriteData[imgId].count())
//                    (m_pDocument->m_CellData[a][s][c]).m_img = m_pDocument->m_SpriteData[imgId][spriteId].m_img;
//                else{
//                    (m_pDocument->m_CellData[a][s][c]).m_img = QImage();
//                    (m_pDocument->m_CellData[a][s][c]).m_pIItem->m_SrcImage = NULL;
//                }

                (m_pDocument->m_CellData[a][s][c]).m_pIItem->recalculateResult();
            }
        }
    }
    if(m_pDocument->m_CellTableWidget)
        m_pDocument->m_CellTableWidget->refineViewNoUndo(m_pDocument->m_CellTableWidget->currentIndex().row());
    m_pDocument->m_pSceneFrameFigure->m_canvas.update();

    refineViewNoUndo(selIndex);
    m_pDocument->m_SpriteTableWidget->refineViewNoUndo(-1);

   qDebug("m_pDocument->m_ImageListModel.m_pList->count() %d", m_pDocument->m_ImageListModel.m_pList->count());
   qDebug("m_pDocument->m_SpriteListModel.m_pList->count() %d", m_pDocument->m_SpriteListModel.m_pList->count());
   qDebug("deleteImage End");
}

void JistTableView::createFakeBmp()
{
    int index = currentIndex().row();
    if (index < 0 )
        return;
    JistCommonModel *dataModel = (JistCommonModel*)(this->model());
    m_pDocument->m_pSrcFigure->creatFakeBMP();
}

void JistTableView::mousePressEvent ( QMouseEvent * event )
{
    this->setFocus();
    //if(m_pDocument->m_AnimaionTableWidget)
    //    const QModelIndex index = m_pDocument->m_AnimaionTableWidget->model()->index(m_pDocument->m_AnimaionTableWidget->m_iSelectIndex, 0, QModelIndex());
    //m_pDocument->m_AnimaionTableWidget->closePersistentEditor(index);
    // 리스트 셀 선택추 리스트 셀 이외의 지역 클릭하고 다시 선택하면 생기는 오작동 제거
    int c = columnAt (event->pos().x() );
    int r = rowAt (event->pos().y());
    if(r != -1 && c != -1)
        QTableView::mousePressEvent(event);
    if(r >= 0 && c >= 0 && selectedIndexes().count() == 0)
        QTableView::setSelection(QRect(event->pos().x(), event->pos().y(), 1, 1),QItemSelectionModel::Select);
}

void JistTableView::mouseReleaseEvent ( QMouseEvent * event )
{
    // 선택시 인덱스 밀림 mouseReleaseEvent시 인덱스 갱신 방지

}

void JistTableView::mouseDoubleClickEvent ( QMouseEvent * event )
{
    QTableView::mouseDoubleClickEvent(event);
    switch(m_eChangeMode)
    {
        case ANIMATIONLIST_CHANGE:
        {
            const QModelIndex index = model()->index(m_iSelectIndex, 0, QModelIndex());
            openPersistentEditor(index);
            break;
        }
    }
}

void JistTableView::keyPressEvent ( QKeyEvent * event )
{
    QTableView::keyPressEvent (event);
    switch(m_eChangeMode)
    {
        case CELLLIST_CHANGE:
        {
            // 신 편집 위젯으로 이동
            if(event->key() == Qt::Key_Alt){// && !event->isAutoRepeat())
                QApplication::setActiveWindow (m_pDocument->m_pSceneFrameFigure );
                m_pDocument->m_pSceneFrameFigure->setFocus();
            }
        }
        break;
        default:
            QTableView::keyPressEvent (event);
    }
}

void JistTableView::setName()
{
    if(this->currentIndex().row() < 0 )
        return;
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    JistCommonData data = m->m_pList->value(index);
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");

    const QString localeStr = codec->toUnicode("이름 바꾸기");
    bool ok = false;
//    QString text = QInputDialog::getText(this, localeStr,
//                                         tr("User name:"), QLineEdit::Normal,
//                                         data.m_Name, &ok);
//    QStringList items;
//    items << data.m_Name;

//    QInputDialog *iDialog = new QInputDialog();
//    QString text = iDialog->getItem(this, localeStr,
//                                         tr("User name:"), items,
//                                         0, true, &ok);
    m_TextEditdialog->setVisible(true);
    m_TextEdit->setPlainText(data.m_Name);
    QString text = m_TextEdit->toPlainText();

   // data.m_Name = text;
    if (ok){
        m->setData(currentIndex(), text, Qt::DisplayRole);
         //m_pDocument->m_AnimationData[m_pDocument->m_iCurrentSceneDataIndex].m_Name = text;
    }

//    if(m_eChangeMode == CELLLIST_CHANGE){
//         data.m_Name = text;
//        //QGraphicsTextItem *textSprite;
//        QPixmap pm(QSize(100,100));
//        //m_pSceneFrameFigure->m_canvas.setBackgroundBrush( pm );
//        //textSprite = new QGraphicsTextItem( data.m_Name, data.m_pIItem, &m_pDocument->m_pSceneFrameFigure->m_canvas );
//        //QFont font( "MS Gothic", 18 );
//        //textSprite->setFont( font );
//        if(!data.m_pIItem->m_TextItem){
//           data.m_pIItem->m_TextItem = new QGraphicsTextItem( data.m_Name, data.m_pIItem, &m_pDocument->m_pSceneFrameFigure->m_canvas );
//           //QFont font(QString("나눔고딕 ExtraBold"), 10 );
//           QTextCodec *codec = QTextCodec::codecForName("UTF-8");
//           QString localeStr = codec->toUnicode("나눔고딕 ExtraBold");
//           QFont font( localeStr, g_FontSize);
//           data.m_pIItem->m_TextItem->setFont( font );
//        }
//        data.m_pIItem->m_TextItem->setPlainText(data.m_Name);
//        QRectF r = data.m_pIItem->m_TextItem->boundingRect();
//        data.m_pIItem->setRect(r);
//        data.m_pIItem->m_TextItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
//        data.m_pIItem->m_TextItem->setPos(-r.width()/2, -r.height()/2);
//        data.m_pIItem->m_TextItem->setDefaultTextColor(QColor(255,255,255));
//    }
//    else if(m_eChangeMode == IMGLIST_CHANGE){
//        QDir dir = QDir::current();
//        QString CurrentPath = dir.absoluteFilePath(data.m_Name);
//        //QString CurrentPath = dir.a + data.m_Name;
//        QFile file(CurrentPath);
//        file.rename(text);

//        // 바뀐 이미지 적용하기
//        QString changedPath = dir.absoluteFilePath(text);
//        QImage tempImg(changedPath);
//        if(!tempImg.isNull()){
//            m->setData(currentIndex(), tempImg, Qt::UserRole + 2);
//            for(int sCnt = 0; sCnt < m_pDocument->m_SpriteData[index].count(); sCnt++){
//                JistCommonData &sprite = m_pDocument->m_SpriteData[index][sCnt];
//                sprite.m_img = tempImg.copy(sprite.m_Rect);
//                m_pDocument->m_SpriteData[index][sCnt].m_img = sprite.m_img;
//                m_pDocument->m_SpriteTableWidget->selectRow(sCnt);
//                m_pDocument->m_SpriteListModel.setData(m_pDocument->m_SpriteTableWidget->currentIndex(), sprite.m_img, Qt::UserRole + 2);
//            }
//            m_pDocument->changeSpriteList(index);
//        }
//    }
}

void JistTableView::setOptCutWider()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());

    for(int sCnt = 0; sCnt < m->m_pList->count(); sCnt++){
        selectRow(sCnt);
        setOptCut_WW();
        setOptCut_WH();
//        JistCommonData &sprite = m_pDocument->m_SpriteData[index][sCnt];
//        sprite.m_img = tempImg.copy(sprite.m_Rect);
//        m_pDocument->m_SpriteTableWidget->selectRow(sCnt);
//        m.setData(m_pDocument->m_SpriteTableWidget->currentIndex(), sprite.m_img, Qt::UserRole + 2);
    }
}

// 스프라이트 리스트 정리
void JistTableView::spriteListRefine()
{
    int index = currentIndex().row();
    if (index < 0 )
        return;
    JistTableView *imgTable = m_pDocument->m_ImageTableWidget;
    JistCommonModel* m = (JistCommonModel*)(imgTable->model());
    // 모든 이미지에 대하여 정리
    for(int imgCnt = 0; imgCnt < m->m_pList->count(); imgCnt++){
         m_pDocument->m_ImageTableWidget->selectRow(imgCnt);
        JistCommonModel *dataModel = (JistCommonModel*)(this->model());
        JistCommonData imgdata  =  m->m_pList->value(imgCnt);
        // 체크박스 체크되어있지 않으면 이미지 리스트 유지 스프라이트 정리를 하지않음
        if(!imgdata.m_bVisible)
            continue;

        int currentImgIndex = m_pDocument->m_iCurrentSpriteDataIndex;
        for(int currentSpriteIndex = 0; currentSpriteIndex < dataModel->rowCount(); currentSpriteIndex++)
        {
            selectRow(currentSpriteIndex);
            bool isUsed = false;
            // 리스트뷰및 신뷰 갱신
            for(int a = 0; a < m_pDocument->m_CellData.count() && !isUsed; a++){
                for(int s = 0; s < m_pDocument->m_CellData[a].count() && !isUsed; s++){
                    for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                        int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                        int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;
                        // 지워진 스프라이트를 참조하는 셀 정리
                        if(currentImgIndex == imgId && currentSpriteIndex == spriteId){
                            isUsed = true;
                            break;
                        }
                    }
                }
            }
            if(!isUsed){
                JistDocumentHandler *handler = JistDocumentHandler::instance();
                handler->removeSprite_Fast();
                currentSpriteIndex--;
            }
        }
        // 제거하고 리스트 순서 정리
        if(dataModel->rowCount() == 0){
            for(int k = 0; k < 10; k++){
                m_pDocument->m_ImageTableWidget->moveItemDown();
            }
            imgCnt--;
            imgTable->deleteImage();
        }
    }
    m_pDocument->m_CellTableWidget->refineViewNoUndo(m_pDocument->m_CellTableWidget->currentIndex().row());
    m_pDocument->m_pSceneFrameFigure->m_canvas.update();

    //refineViewNoUndo(selIndex);
}
void JistTableView::accept()
{
    m_isDialogBtnOk = true;
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    JistCommonData data = m->m_pList->value(index);
    QString text = m_TextEdit->toPlainText();
    if (m_isDialogBtnOk ){
        m->setData(currentIndex(), text, Qt::DisplayRole);
         //m_pDocument->m_AnimationData[m_pDocument->m_iCurrentSceneDataIndex].m_Name = text;
    }

    if(m_eChangeMode == CELLLIST_CHANGE){
         data.m_Name = text;
        //QGraphicsTextItem *textSprite;
        QPixmap pm(QSize(100,100));
        //m_pSceneFrameFigure->m_canvas.setBackgroundBrush( pm );
        //textSprite = new QGraphicsTextItem( data.m_Name, data.m_pIItem, &m_pDocument->m_pSceneFrameFigure->m_canvas );
        //QFont font( "MS Gothic", 18 );
        //textSprite->setFont( font );
        if(!data.m_pIItem->m_TextItem){
           //data.m_pIItem->m_TextItem = new QGraphicsTextItem( data.m_Name, data.m_pIItem, &m_pDocument->m_pSceneFrameFigure->m_canvas );
           data.m_pIItem->m_TextItem = new QGraphicsTextItem( data.m_Name, data.m_pIItem);           //QFont font(QString("나눔고딕 ExtraBold"), 10 );
           QTextCodec *codec = QTextCodec::codecForName("UTF-8");
           QString localeStr = codec->toUnicode("나눔고딕 ExtraBold");
           QFont font( localeStr, g_FontSize);
           data.m_pIItem->m_TextItem->setFont( font );
        }
        data.m_pIItem->m_TextItem->setPlainText(data.m_Name);
        QRectF r = data.m_pIItem->m_TextItem->boundingRect();
        data.m_pIItem->setRect(r);
        data.m_pIItem->m_TextItem->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
        if(!data.m_pIItem->m_iAnchor)
            data.m_pIItem->m_TextItem->setPos(-r.width()/2, -r.height()/2);
        if(data.m_pIItem->m_composition_mode == 3)// QPainter::CompositionMode_Source
            data.m_pIItem->m_TextItem->setDefaultTextColor(QColor(255,255,255));
    }
    else if(m_eChangeMode == IMGLIST_CHANGE){
        QDir dir = QDir::current();
        QString CurrentPath = dir.absoluteFilePath(data.m_Name);
        //QString CurrentPath = dir.a + data.m_Name;
        QFile file(CurrentPath);
        file.rename(text);

        // 바뀐 이미지 적용하기
        QString changedPath = dir.absoluteFilePath(text);
        QImage tempImg(changedPath);
        if(!tempImg.isNull()){
            m->setData(currentIndex(), tempImg, Qt::UserRole + 2);
            for(int sCnt = 0; sCnt < m_pDocument->m_SpriteData[index].count(); sCnt++){
                JistCommonData &sprite = m_pDocument->m_SpriteData[index][sCnt];
                sprite.m_img = tempImg.copy(sprite.m_Rect);
                m_pDocument->m_SpriteData[index][sCnt].m_img = sprite.m_img;
                m_pDocument->m_SpriteTableWidget->selectRow(sCnt);
                m_pDocument->m_SpriteListModel.setData(m_pDocument->m_SpriteTableWidget->currentIndex(), sprite.m_img, Qt::UserRole + 2);
            }
            m_pDocument->changeSpriteList(index);
        }
    }
    m_TextEditdialog->accept();
}

void JistTableView::reject()
{
    m_isDialogBtnOk = false;
    m_TextEditdialog->reject();
}


JistCommonData* JistTableView::GetCurrentData()
{
    int index = currentIndex().row();
    JistCommonModel* m = (JistCommonModel*)(this->model());
    QList< JistCommonData > *pList = m->m_pList;
    JistCommonData *data = m_pDocument->getCurrentSpriteData();
    return data;
}
